//
//  ZYOAuthViewController.swift
//  WeiBo
//
//  Created by zhangyu on 16/9/21.
//  Copyright © 2016年 zhangyu. All rights reserved.
//

import UIKit
import SVProgressHUD

let WeiboAppKey = "2258702084"
let WeiboRedirect_Uri = "http://www.sharesdk.cn"
let WeiboAppSecret = "eb961d893aa470955bc3f5d5d4be7dbb"

class ZYOAuthViewController: UIViewController {
    
    private lazy var webView:UIWebView = UIWebView()
    override func loadView() {
        //  解决底部webView黑条
        //  改成透明解决黑条问题
        webView.isOpaque = false
        //设置代理
        webView.delegate = self
        view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        requestLogin()
        setupNavUI()
    }
    //请求第三方登录
    private func requestLogin(){
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        let urlRequest = URLRequest(url:URL(string: url)!)
        webView.loadRequest(urlRequest)
        
    }
    
    //  设置导航栏按钮
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        title = "微博"
    }
    
    //  MARK: -- 点击事件处理
    @objc private func cancelAction() {
        
        //  点击取消的时候让等待指示器删除
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autoFillAction() {
        
        print("自动填充")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '15066152593';document.getElementById('passwd').value = '8010'")
    }
        
    
}

//MARK: --UIWebViewDelegate
extension ZYOAuthViewController:UIWebViewDelegate{
    //开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
    SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
    SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    SVProgressHUD.dismiss()
    }
    //将要加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //判断url是否合法
        guard let url = request.url else {
            print("url 为 nil")
            return false
        }
        print(url.absoluteString)
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        if let query = url.query , query.hasPrefix("code=") {
            let code = query.substring(from: "code=".endIndex)
//            print(code)
//            requestAccesstoken(code: code)
            ZYUserAccountViewModel.sharedUserAccountViewModel.requestAccesstoken(code: code, callBack: { (isSuccess) in
                
                if isSuccess {
                    //  表示登录成功
                    print("登录成功")
                    //  要等到dismis完成以后在发送切换根视图控制器的操作
                    self.dismiss(animated: false, completion: {
                        //  进入欢迎页面
                        
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                }  
            })
        }else {
            //  取消授权
            dismiss(animated: true, completion: nil)
        }
        return false
    }
    
}
